package com.heima.search.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.feign.BehaviorFeign;
import com.heima.search.mapper.ApUserSearchMapper;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@SuppressWarnings("ALL")
/**
 * @Description :
 * @author     :LD
 */
@Service
@Transactional
@Log4j2
public class ApUserSearchServiceImpl extends ServiceImpl<ApUserSearchMapper, ApUserSearch> implements ApUserSearchService {
    @Autowired
    private BehaviorFeign behaviorFeign;

    /**
     * 保存用户搜索历史记录
     * @param entry
     * @param searchWords
     */
    @Override
    @Async("taskExecutor")
    public void insert(Integer entryId, String searchWords) {
        //1 检查参数
        if (entryId==null || StringUtils.isBlank(searchWords)){
            throw new RuntimeException("保存搜索关键字失败");
        }
        //2 查询搜索记录
        ApUserSearch apUserSearch = getOne(Wrappers.<ApUserSearch>lambdaQuery()
                .eq(ApUserSearch::getEntryId, entryId)
                .eq(ApUserSearch::getKeyword, searchWords));
        //3 存在，则更新状态
        if (apUserSearch!=null && apUserSearch.getStatus()==1){
            log.info("关键字已经存在，无需再次保存");
            return;
        }else if (apUserSearch!=null && apUserSearch.getStatus()==0){
            apUserSearch.setStatus(1);
            updateById(apUserSearch);
            return;
        }
        //4 不存在，新增数据
        apUserSearch = new ApUserSearch();
        apUserSearch.setEntryId(entryId);
        apUserSearch.setCreatedTime(new Date());
        apUserSearch.setKeyword(searchWords);
        apUserSearch.setStatus(1);
        save(apUserSearch);
    }

    /**
     * 查询搜索历史记录
     * @param userSearchDto
     * @return
     */
    @Override
    public ResponseResult findUserSearch(UserSearchDto userSearchDto) {
        //1 检查参数
        if(userSearchDto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (userSearchDto.getPageSize()>50){
            userSearchDto.setPageSize(50);
        }
        //2 查询行为实体
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApBehaviorEntry apBehaviorEntry = behaviorFeign.getBehaviorEntry(user.getId(), userSearchDto.getEquipmentId());
        if (apBehaviorEntry==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //3 分页查询
        IPage page1 = new Page(0, userSearchDto.getPageSize());
        IPage page = page(page1, Wrappers.<ApUserSearch>lambdaQuery()
                .eq(ApUserSearch::getEntryId,apBehaviorEntry.getId())
                .eq(ApUserSearch::getStatus,1));
        //4 数据返回
        return ResponseResult.okResult(page.getRecords());
    }

    @Override
    public ResponseResult delUserSearch(UserSearchDto userSearchDto) {
        //1 检查参数
        if (userSearchDto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 更新当前记录状态 status 0
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApBehaviorEntry apBehaviorEntry = behaviorFeign.getBehaviorEntry(user.getId(), userSearchDto.getEquipmentId());
        if (apBehaviorEntry==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        update(Wrappers.<ApUserSearch>lambdaUpdate()
                .eq(ApUserSearch::getEntryId,apBehaviorEntry.getId())
                .eq(ApUserSearch::getId,userSearchDto.getId())
                .set(ApUserSearch::getStatus,0));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
